<template>
  <div class="box">
    <div class="top">
      <h1 class="title01">个人中心</h1>
    </div>
    <!-- 主体 -->
    <div class="content">
      <!-- 头像 -->
      <div class="userimg">
        <span>头像:</span>
        <img @click="dialogVisible = true" :src="userinfo.headphoto" alt="" />
      </div>

      <!-- 信息 -->
      <div class="information">
        <el-form title="用户信息" column="1">
          <el-form-item label="用户名：">
            <span>{{ userinfo.username }}</span>
            <!-- <input v-if="ReviseValue" v-model="userinfo.username" type="text" /> -->
          </el-form-item>
          <el-form-item label="职位："
            ><span>{{ rname }}</span></el-form-item
          >
          <el-form-item label="手机号：">
            <span v-if="!ReviseValue">{{ userinfo.phone }}</span>
            <input
              v-if="ReviseValue"
              v-model="userinfo.phone"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="11"
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item label="备注：" class="remark">
            <span v-if="!ReviseValue">{{ userinfo.remark || "---" }}</span>
            <textarea
              rows="5"
              cols="40"
              v-if="ReviseValue"
              v-model="userinfo.remark"
              type="text"
            />
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" v-if="!ReviseValue" @click="Revise('edit')">
            修改信息
          </el-button>
          <el-button type="primary" v-if="ReviseValue" @click="Revise('save')">
            保存
          </el-button>

          <el-button
            type="primary"
            v-if="ReviseValue"
            @click="Revise('cancel')"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            v-if="!ReviseValue"
            @click="dialogVisiblePwd = true"
          >
            修改密码
          </el-button>
        </div>
      </div>
    </div>
  </div>

  <!-- 头像弹出框 -->
  <el-dialog v-model="dialogVisible" title="修改头像" width="500">
    <el-upload
      action="/user/upload"
      ref="upload"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-success="handelSuccess"
      v-model:file-list="fileList"
      :multiple="false"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handelSave"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogVisibleimg">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>

  <!-- 修改密码弹窗 -->
  <el-dialog
    v-model="dialogVisiblePwd"
    title="修改密码"
    width="500"
    :before-close="handleClose"
  >
    <el-form
      :model="form"
      ref="ruleFormRefPut"
      :rules="soilRules"
      class="updataForget"
    >
      <el-form-item
        label="旧密码："
        :label-width="formLabelWidth"
        prop="oldPassword"
      >
        <el-input v-model="form.oldPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="新密码："
        :label-width="formLabelWidth"
        prop="password"
      >
        <el-input v-model="form.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="确认密码："
        :label-width="formLabelWidth"
        prop="ispassword"
      >
        <el-input
          v-model="form.ispassword"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisiblePwd = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { putUpdata, getdata, putPwd } from "@/api/Personal";
import router from "@/router";
const dialogVisiblePwd = ref(false);
const dialogVisible = ref(false);
const dialogVisibleimg = ref(false);
const ReviseValue = ref(false);
const dialogImageUrl = ref("");
const infodata = JSON.parse(sessionStorage.getItem("userinfo"));
const userinfo = reactive({
  uid: "",
  username: "",
  password: "",
  phone: "",
  remark: "",
  headphoto: "",
  status: "1",
});
const fileList = ref([
  {
    name: infodata.headphoto,
    url: infodata.headphoto,
  },
]);
const upload = ref(null);
const rname = ref(sessionStorage.getItem("rname"));

// 修改保存函数
const Revise = (val) => {
  if (val == "edit") {
    // 如果是修改则切换输入框
    ReviseValue.value = true;
  } else if (val == "cancel") {
    // 是取消就恢复原始数据
    userinfo.uid = infodata.uid;
    userinfo.username = infodata.username;
    userinfo.password = infodata.password;
    userinfo.phone = infodata.phone;
    userinfo.remark = infodata.remark;
    userinfo.headphoto = infodata.headphoto;
    ReviseValue.value = false;
  } else {
    // console.log(userinfo);
    //  保存，发送请求向服务器修改数据
    // console.log(userinfo.phone.toString().length);
    if (userinfo.remark.length > 50) {
      ElMessage({
        message: "备注不能超过50个字符",
        type: "error",
      });
    } else {
      if (userinfo.phone.toString().length < 11) {
        ElMessage({
          message: "不是规范的电话号",
          type: "error",
        });
      } else {
        putUpdata(userinfo).then(
          (res) => {
            if (res.code == 200) {
              getdata(userinfo.uid).then((res) => {
                infodata.phone = userinfo.phone;
                infodata.remark = userinfo.remark;
                sessionStorage.setItem("userinfo", JSON.stringify(infodata));
                infodata = JSON.parse(sessionStorage.getItem("userinfo"));
                updataUserinfo();
                ElMessage({
                  message: "保存成功",
                  type: "success",
                });
                router.push("/index/personal");
              });
            } else {
              ElMessage({
                message: "修改失败",
                type: "error",
              });
            }
          },
          (err) => {
            ElMessage({
              message: "修改失败",
              type: "error",
            });
          }
        );
        ReviseValue.value = false;
      }
    }
  }
};

// 预览图片
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisibleimg.value = true;
};

//上传图片成功更新用户头像，并开启输入框
const handelSuccess = (uploadFile) => {
  console.log(uploadFile);
  console.log(fileList.value);
  if (fileList.value.length > 1) {
    fileList.value.splice(0, 1);
  }
  userinfo.headphoto = uploadFile.data;
  ReviseValue.value = true;
};

// 关闭上传图片弹窗
const handelSave = () => {
  dialogVisible.value = false;
  ReviseValue.value = true;
};

// 更新用户信息函数
function updataUserinfo() {
  // infodata = JSON.parse(sessionStorage.getItem("userinfo"));
  userinfo.uid = infodata.uid;
  userinfo.username = infodata.username;
  userinfo.password = infodata.password;
  userinfo.phone = infodata.phone;
  userinfo.remark = infodata.remark;
  userinfo.headphoto = infodata.headphoto;
}

// 规则
// 自定义校验规则 方法
let relusList = (rules, value, callback) => {
  //if 对两个输入框的value值进行必填校验
  if (!form.ispassword || !form.password) {
    return callback(new Error("确认密码不为空"));
    // 对第二个输入框进行正则校验
  } else if (form.ispassword !== form.password) {
    callback(new Error("密码必须一致"));
  } else {
    return callback();
  }
};
// 修改密码表单
const form = reactive({
  uid: infodata.uid,
  oldPassword: "",
  password: "",
  ispassword: "",
});

//密码表单校验输入的内容
const soilRules = reactive({
  oldPassword: [
    {
      required: true,
      message: "旧密码不为空",
      trigger: "blur",
    },
  ],
  password: [{ required: true, message: "新密码不为空", trigger: "blur" }],
  ispassword: [{ required: true, validator: relusList, trigger: "blur" }],
});

// 修改密码

function handleUpdate() {
  if (
    form.password !== "" ||
    form.oldPassword !== "" ||
    form.ispassword !== ""
  ) {
    if (form.password.length < 6 || form.ispassword.length < 6) {
      ElMessage({
        message: "新密码长度不小于6",
        type: "error",
      });
    } else if (form.password.length > 16 || form.ispassword.length > 16) {
      ElMessage({
        message: "新密码长度不大于16",
        type: "error",
      });
    } else {
      if (form.oldPassword == form.password) {
        ElMessage({
          message: "新旧密码相同，请重新输入",
          type: "error",
        });
      } else {
        if (form.password != form.ispassword) {
          ElMessage({
            message: "新密码与确认密码不一致",
            type: "error",
          });
        } else {
          putPwd(form).then((res) => {
            if (res.code == 200) {
              ElMessage({
                message: "修改密码成功",
                type: "success",
              });
              form.oldPassword = "";
              form.ispassword = "";
              form.password = "";
              dialogVisiblePwd.value = false;
            } else {
              ElMessage({
                message: res.data,
                type: "error",
              });
            }
          });
        }
      }
    }
  } else {
    ElMessage({
      message: "旧密码或新密码不为空",
      type: "error",
    });
  }
}

onMounted(() => {
  updataUserinfo();
});
</script>

<style lang="scss" scoped>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

input[type="number"] {
  -moz-appearance: textfield;
}
/*大盒子样式 */
.box {
  display: flex;
  flex-direction: column;
  .content {
    margin: 20px auto;
    padding: 10px 20px;
    background-color: #efefef;
    border-radius: 10px;
    width: 70%;
    height: 100%;
    .userimg {
      cursor: pointer;
      display: flex;
      align-items: center;
      margin: 20px 0;
      img {
        margin-left: 20px;
        width: 100px;
        height: 100px;
        border-radius: 50%;
      }
    }
    .information {
      // display: flex;
      // justify-content: space-between;

      font-size: 30px;
      .el-form-item {
        margin-top: 20px;
        height: 20px;
        width: 30%;
        height: 30%;
        span {
          display: inline-block;
        }
        input {
          padding: 5px 10px;
          width: 100%;
          height: 100%;
          border-radius: 5px;
          border: 1px solid #409eff;
        }
        textarea {
          resize: none;
          border-radius: 5px;
          border: 1px solid #409eff;
        }
      }
    }
  }
}
:deep(.el-form-item__label) {
  display: inline-block;
  width: 100px;
}
</style>
